<template>
  <view>

    <uni-list>
      <block v-for="c in chats">

        <view>


          <uni-list-chat @click="goChat(c.id)" clickable='true' :title="c.nickName" :avatar="c.avatar">
          </uni-list-chat>


        </view>

      </block>
    </uni-list>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userid: 14,
      chats: [],
      sMsg: [],
      news: [],

    }
  },

  computed: {
    //监听接收到的消息
    getAccept() {
      return this.$websocket.getters.getAccept
    }
  },
  watch: {
    'getAccept': {
      //处理接收到的消息
      handler: function () {
        let that = this
        console.log("接收到新msg")
        this.new = this.getAccept;
        console.log(this.new)
        this.change(this.getAccept);
      }
    }
  },
  created() {

    var user = uni.getStorageSync('loginUser')
    console.log(user);
    console.log(user.id);
    if (user == null) {
      console.log("user为空");
      uni.redirectTo({
        url: '/pages/login/login'
      });
    }
    this.$websocket.commit("addUsers", user)
    this.$websocket.state.uid = user.id
    this.$websocket.commit('checkConnection', user.id)
    this.userid = user.id;
    console.log(this.userid + "  xiaoxi")


    this.getChats();
  },
  methods: {
    getChats() {
      var a = this;
      uni.request({
        url: 'http://127.0.0.1:800/mhs/room/getChats/' + this.userid,
        header: {
          token: uni.getStorageSync('token')
        },
        success: (res) => {
          //	this.chats = res.data.data;

          console.log(res.data);

          for (var b of res.data.data) {
            if (b.consulant.id == this.userid) {

              /* b.consumer.flag = 0; */
              this.chats.push(b.consumer);
              this.$websocket.commit('addUsers', b.consumer);
              //把最新消息存到对象例里
            } else {
              console.log(b.consulant);
              //b.consulant.flag = 0;
              this.chats.push(b.consulant);
              this.$websocket.commit('addUsers', b.consulant);
            }
          }

          console.log(this.chats);
        }
      })
    },
    change(b) {
      this.chats.forEach((a) => {
        if (b.fromUid == a.id) {
          //a.flag = 1;
          // a.message = b;

          console.log(this.new.fromUid + "有新消息")
          console.log(a);
        }


      });
      this.$forceUpdate()
    },
    goChat(id) {
      uni.redirectTo({
        url: '/pages/chat/chat?id=' + id
      });
    },
  },
}
</script>

<style>

</style>